package com.sx.core.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Calendar;
import java.util.Date;

/**
 * Created by lihao on 16/4/10.
 */
public class WxRequestInstance {
    private Log log= LogFactory.getLog(getClass());
    private volatile static WxRequestInstance instance=null;
    private String wxToken;
    private String ticket;
    private Date ticketExpred;
    private Date tokenExipred;
    private String appId;
    private String secret;
    private WxRequestInstance(String appId, String secret){
        this.appId=appId;
        this.secret=secret;
    }
    public static WxRequestInstance getInstance(){
        return instance;
    }
     public static WxRequestInstance getInstance(String appId,String secret){
        if(instance==null){
            synchronized (WxRequestInstance.class){
                if(instance==null){
                    instance=new WxRequestInstance(appId,secret);
                    instance.initTicket();
                }
            }
        }
        return instance;
    }

    private void initBaseToken(){
        JSONObject baseToken=new WxJsUtils().getBaseToken(appId,secret);
        if(baseToken==null){
            log.error("get wx base token error");
            return;
        }
        this.wxToken=baseToken.getString("access_token");
        if(wxToken==null){
            log.error("get wx base token error");
            return;
        }
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.SECOND,baseToken.getInteger("expires_in")-20*60);
        this.tokenExipred=calendar.getTime();
    }
    private void initTicket(){
        this.ticket=new WxJsUtils().getJsTicket(getBaseToken());
        if(ticket==null){
            log.error("get wx ticket error");
            return;
        }
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.SECOND,7000);
        this.ticketExpred=calendar.getTime();
    }
    public synchronized String getBaseToken(){
        if(tokenExipred==null || new Date().after(tokenExipred)){
            initBaseToken();
        }
        return wxToken;
    }
    public synchronized String getTicket(){
        if(ticketExpred==null || new Date().after(ticketExpred)){
            initTicket();
        }
        return ticket;
    }

}
